from QQLoginTool.QQtool import OAuthQQ
from django.shortcuts import render

# Create your views here.
from rest_framework import status
from rest_framework.response import Response
from rest_framework.views import APIView
from django.conf import settings
import logging
from rest_framework_jwt.settings import api_settings

from .utils import generate_save_user_token
from .models import OAuthQQUser
from . import serializers
logger = logging.getLogger('django')


class OauthUserView(APIView):
    #实现oauth2.0 使用code获取access_token
    #再使用access_token 获取openid
    def get(self,request):

        # 提取ｃｏｄｅ请求参数
        code = request.query_params.get('code')
        if not code:
            return Response({'message':'缺少code'},status=status.HTTP_400_BAD_REQUEST)
        #创建ＳＤＫ对象
        oauth = OAuthQQ(client_id=settings.QQ_CLIENT_ID, client_secret=settings.QQ_CLIENT_SECRET,
                        redirect_uri=settings.QQ_REDIRECT_URI)
        # 使用code向ＱＱ服务器请求access_token
        try:
            access_token = oauth.get_access_token(code)
        # 使用access_token向ＱＱ服务器请求openid
            open_id = oauth.get_open_id(access_token)
        except Exception as e:
            logger.info(e)
            return Response({'message':'QQ服务器错误'},status=status.HTTP_503_SERVICE_UNAVAILABLE)
        # 使用openid查询该ＱＱ用户是否在美多商城绑定过用户
        try:
            oauthqquser_model = OAuthQQUser.objects.get(openid = open_id)
        except OAuthQQUser.DoesNotExist:
            # 如果openid用户没有绑定美多商城用户　创建用户并绑定到openid
            token_openid = generate_save_user_token(open_id)
            return Response({'access_token':token_openid})

        else:
            # 如果openid已经绑定过美多商城用户，直接生成JWT token　，并返回
            #获取绑定了的user
            qq_user = oauthqquser_model.user
            jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
            jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
            #使用注册后的user信息　　生成载荷
            payload = jwt_payload_handler(qq_user)
            # 使用载荷，生成token
            token = jwt_encode_handler(payload)
            return Response({
                'token':None,
                'username':qq_user.username,
                'user_id':qq_user.id
            })

    def post(self,request):
        """使用openid绑定用户"""
        #创建序列化器对象
        serializer = serializers.QQAuthUserSerializer(data=request.data)

        #开启校验
        serializer.is_valid(raise_exception=True)
        #执行并保存
        qq_user = serializer.save()

        #绑定用户成功  生成JWT 并保存
        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
        # 使用注册后的user信息　　生成载荷
        payload = jwt_payload_handler(qq_user)
        # 使用载荷，生成token
        token = jwt_encode_handler(payload)
        return Response({
            'token': None,
            'username': qq_user.username,
            'user_id': qq_user.id
        })

"""url(r('qq/authorization/$',views.OauthURLView.as_view())"""
class OauthURLView(APIView):
    """返回QQ扫码登陆链接"""

    def get(self,request):

        #获取ｎｅｘｔ参数
        # next表示从哪个页面进入到的登录页面，将来登录成功后，就自动回到那个页面
        next = request.query_params.get('next')

        # 获取QQ登录页面网址(创建SDK对象)
        oauth = OAuthQQ(client_id=settings.QQ_CLIENT_ID, client_secret=settings.QQ_CLIENT_SECRET,
                        redirect_uri=settings.QQ_REDIRECT_URI, state=next)
        #使用ＳＤＫ方法，得到ＱＱ扫码登陆的页面
        login_url = oauth.get_qq_url()
        #返回ＱＱ扫码登录的链接
        return Response({"login_url":login_url})